<!-- 组织详情右侧内容组件 -->
<template>
  <div class="header">
    <div class="box1">
      <div
        :style="{
          marginBottom: '10px',
          display: 'flex',
          justifyContent: 'space-between'
        }"
      >
        <div>
          <a-space>
            <h1
              :style="{
                lineHeight: '28px'
              }"
            >
              {{ organizationInfo.name }}
            </h1>
            <a-tag color="#165DFF">
              {{
                organizationList.find(
                  (item: any) => item.id == organizationInfo.type
                )?.name
              }}
            </a-tag>
          </a-space>
        </div>
        <a-space class="options">
          <a-button type="primary" @click="goManagement">人员管理</a-button>
          <!-- <a-button type="outline" @click="staffingChangeVisible = true"
            >调整编制</a-button
          > -->

          <a-button
            type="outline"
            @click="addPosition"
            v-if="organizationInfo.ownerId !== 1"
            >新增职位</a-button
          >
          <!-- <a-button type="outline">更多功能</a-button> -->
        </a-space>
      </div>
      <div>
        <a-space>
          <template #split>
            <a-divider direction="vertical" />
          </template>
          <div>
            <span class="info-title">当前编制：</span>
            <span
              :style="{
                color: '#165DFF'
              }"
              >{{ organizationInfo.headcount }}
            </span>
          </div>
          <div>
            <span class="info-title">超编/缺编：</span>
            <span
              :style="{
                color: '#F53F3F'
              }"
              >{{ organizationInfo.overNum }}</span
            >
          </div>
          <span class="info-title"
            >上级组织：<span
              :style="{
                color: '#1D2129'
              }"
              >{{ organizationInfo.superiorOrganization }}</span
            ></span
          >
          <span class=""
            >负责人：<span
              :style="{
                color: '#1D2129'
              }"
              >{{ organizationInfo.responserName }}</span
            ></span
          >
        </a-space>
      </div>
    </div>
    <div style="position: relative">
      <a-collapse
        class="box2"
        :default-active-key="['1']"
        :bordered="false"
        v-model:active-key="isCollapse"
        :show-expand-icon="false"
      >
        <a-collapse-item header="" key="1">
          <!-- <template #extra>
            {{ isCollapse == '1' ? '收起' : '展开员工统计数据' }}
          </template> -->
          <div
            style="
              display: flex;
              gap: 10px;
              margin-bottom: 10px;
              margin-right: 20px;
            "
          >
            <HumenNumberCard
              :list="numberList.list1"
              color1="#ecf6ff"
              color2="#165dff"
              style="flex: 2"
            />
            <HumenNumberCard
              :list="numberList.list2"
              color1="#F5FDF2"
              color2="#82d62c"
              style="flex: 1.5"
            />
            <HumenNumberCard
              :list="numberList.list3"
              color1="#FFF7F0"
              color2="#f5b45b"
              style="flex: 1"
            />
          </div>
          <a-space direction="vertical" fill>
            <a-tag closable color="blue" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：当前组织已接近控编人数上线，请注意控制人员规模，避免超出编制。</span
              >
            </a-tag>
            <a-tag closable color="gold" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：控编人数已经达到人数上限，不可以新增人员。</span
              >
            </a-tag>
            <a-tag closable color="red" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：控编人数已经超出人数上限，请优化组织结构。</span
              >
            </a-tag>
          </a-space>
        </a-collapse-item>
      </a-collapse>
      <div
        class="collapseBtn"
        :style="{
          top: isCollapse === '1' ? '60px' : '0'
        }"
      >
        <a-tooltip
          content="展开员工统计数据"
          v-if="isCollapse !== '1'"
          position="left"
        >
          <icon-caret-right @click="changeCollapse" />
        </a-tooltip>
        <a-tooltip content="收起" v-else position="left">
          <icon-caret-down @click="changeCollapse" />
        </a-tooltip>
      </div>
    </div>
  </div>
  <div class="container">
    <a-tabs lazy-load type="rounded">
      <a-tab-pane key="1" title="组织信息">
        <OrganizationInfo></OrganizationInfo>
      </a-tab-pane>
      <a-tab-pane key="2" title="组织内职位">
        <OrganizationJobs></OrganizationJobs>
      </a-tab-pane>
      <a-tab-pane key="3" title="组织权限">
        <OrganizationAuthority></OrganizationAuthority>
      </a-tab-pane>
      <a-tab-pane key="4" title="员工照片墙">
        <OrganizationPhotos></OrganizationPhotos>
      </a-tab-pane>
      <a-tab-pane key="5" title="操作历史">
        <OrganizationHistory></OrganizationHistory>
      </a-tab-pane>
    </a-tabs>
  </div>

  <AddPosition
    v-model:visible="postionAddVisiable"
    @positionAddEmit="positionAddEmit"
    :list="currPositionData"
  ></AddPosition>
  <StaffingChangeDrawer
    v-model:visible="staffingChangeVisible"
    @staffingChangeEmit="staffingChangeEmit"
    :data="organizationInfo"
  ></StaffingChangeDrawer>
</template>

<script lang="ts" setup>
import { OrganizationPatternSearch } from '@/apis/management/organization/baseSetting/organizationalType';
import {
  PostPosition,
  PostPositionStandard,
  PostPositionMerge
} from '@/apis/management/organization/positionManagement';
import {
  GetOrganizationListDetail,
  PutOrganizationDetailHeadCount
} from '@/apis/management/organization/organizationManagement';
import { GetHumanRosterDetail } from '@/apis/management/human/humanRoster';
import { getFlatDept } from '@/utils/common';
import OrganizationInfo from './Components/OrganizationInfo/index.vue';
import OrganizationJobs from './Components/OrganizationJobs/index.vue';
import OrganizationPhotos from './Components/OrganizationPhotos/index.vue';
import OrganizationHistory from './Components/OrganizationHistory/index.vue';
import AddPosition from '../../../../../Components/AddPosition/index.vue';
import StaffingChangeDrawer from './Components/StaffingChangeDrawer/index.vue';
import OrganizationAuthority from './Components/OrganizationAuthority/index.vue';

const route = useRoute();
const router = useRouter();
// 档案id
let id = Number(route.query.id);
let ownerType = Number(route.query.ownerType);

onBeforeRouteUpdate((to) => {
  id = Number(to.query.id);
  ownerType = Number(to.query.ownerType);
  getData();
});

// 储存组织信息
const organizationInfo = ref({
  name: '', // 组织名称,
  overNum: 0, // 超编缺编,
  headcount: 0, // 当前编制
  superiorOrganization: '', // 上级组织,
  responserName: '', // 组织负责人,
  type: '', // 组织类型
  companyId: undefined, // 公司id
  positionDept: id, // 所属部门
  ownerId: undefined // 组织类型id 1为公司， 用于判断是否显示新增职位，如果是公司类型则不显示
});

let postionAddVisiable = ref(false), // 新增职位弹出框显示
  staffingChangeVisible = ref(false); // 调整编制弹出框显示

let organizationList: any = ref([]); // 储存组织类型列表

let numberList = reactive({
  list1: [
    {
      name: '在职',
      value: 0
    },
    {
      name: '全职',
      value: 0
    },
    {
      name: '实习生',
      value: 0
    },
    {
      name: '兼职',
      value: 0
    }
  ], // 全职、实习生、兼职
  list2: [
    {
      name: '正式',
      value: 0
    },
    {
      name: '试用期',
      value: 0
    },
    {
      name: '待离职',
      value: 0
    }
  ], // 正式、试用期、预离职
  list3: [
    {
      name: '历史总人数',
      value: 0
    },
    {
      name: '历史已离职',
      value: 0
    }
  ] // 历史总人数、历史已离职
});

const enums = [
  ['在职'],
  ['全职', '实习生', '兼职'],
  ['正式', '试用期', '预离职'],
  ['历史总人数', '历史已离职']
];
let isCollapse = ref('1'); // 是否展开员工统计数据

// 修改折叠面板状态
const changeCollapse = () => {
  if (isCollapse.value === '1') {
    isCollapse.value = '2';
  } else {
    isCollapse.value = '1';
  }
};

const getData = async () => {
  try {
    const [orgDetailRes, orgPatternsRes, flatDeptRes] = await Promise.all([
      // 获取组织详情数据
      GetOrganizationListDetail({ id, ownerType }),
      // 查询组织类型列表
      OrganizationPatternSearch({ pageNumber: 0, pagesize: -1 }),
      // 获取平级组织数据
      getFlatDept()
    ]);

    const orgOwner = orgDetailRes.ownerId;
    const orgCollection = orgDetailRes.useTemplate.collectionModel;
    const flatDeptName = (id: number) =>
      flatDeptRes.find((el) => el.id == id)?.name;

    orgCollection.forEach((item) => {
      item.controlModel.forEach((item2) => {
        const value = item2.ctlValue.ctlValue;
        switch (item2.ctlCode) {
          // 组织名称
          case 'C30BBF36A5AF541F7A2657671DEE2EDD6':
            organizationInfo.value.name = value;
            break;
          // 上级组织
          case 'C073F4F41C46D4CA3AF3BEC1F51A8F410':
            organizationInfo.value.superiorOrganization =
              value == 0 ? '无' : flatDeptName(value);
            break;
          // 组织负责人
          case 'CB0C63F38283045F58FFF1B1EABE5D151':
            organizationInfo.value.responserName = flatDeptRes.find(
              (el) => el.id === id
            )?.responserName;
            break;
          // 组织类型
          case 'C3D33FA57216F4968BDE51C31D623FC09':
            organizationInfo.value.type = value;
            break;
          // 编制人数
          case 'CD25749DBA68E4BF3BCA616DD63751CB7':
            organizationInfo.value.headcount = +value;
            break;
          default:
            break;
        }
      });
    });
    organizationInfo.value.ownerId = orgOwner;
    organizationList.value = orgPatternsRes.content;

    const {
      onJob,
      fullTime,
      practice,
      partTime,
      formal,
      probation,
      waitDepart,
      historyNum,
      historyDepart
    } = orgDetailRes;
    numberList.list1[0].value = onJob;
    numberList.list1[0].value = fullTime;
    numberList.list1[1].value = practice;
    numberList.list1[2].value = partTime;
    numberList.list2[0].value = formal;
    numberList.list2[1].value = probation;
    numberList.list2[2].value = waitDepart;
    numberList.list3[0].value = historyNum;
    numberList.list3[1].value = historyDepart;
  } catch (error) {
    console.log(error);
  }
};
getData();

const goManagement = () => {
  router.push({
    name: 'OrganizationPersonManagement',
    params: {
      id,
      name: organizationInfo.value.name
    }
  });
};

// 调整编制弹出框自定义事件
const staffingChangeEmit = async (data: { id: number; num: number }[]) => {
  try {
    await PutOrganizationDetailHeadCount({
      positions: data
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

let currPositionData = ref({
  id
});
// 新增职位弹出框
const addPosition = () => {
  postionAddVisiable.value = true;
};

// 将控件赋值
const pushControl = (
  organizationTemplateCtlValue: any,
  templateId: number,
  collectionData: any,
  controlData: any,
  value: any
) => {
  organizationTemplateCtlValue.push({
    templateId,
    subCode: collectionData.subCode,
    subId: collectionData.id,
    ctlCode: controlData.ctlCode,
    ctlId: controlData.id,
    ctlValue: String(value)
  });
};

const isAddPositionStand = async (formData: any, templateDetail: any) => {
  const positionLibraryReq = templateDetail.map(
    (item1: any, index1: number) => {
      const temp = formData;
      const templateId = item1.id;

      const positionLibrary = {
        ...temp,
        templateUseId: templateId
      };
      const organizationTemplateCtlValue: any = [];

      item1.collectionModel.forEach((item2: any) => {
        item2.controlModel.forEach((item3: any) => {
          switch (item3.ctlCode) {
            // 职位名称
            case 'C2818BAA63AE848AA845DA2E81ECB1843':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.name
              );
              break;
            // 职位编码
            case 'CB25F6DA9F83C4424BBC37E8756BB871E':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionCode
              );
              break;
            // 职位类别
            case 'C63EC32DCE9CC4BE6AC7649E23234A542':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionTypeId
              );
              break;
            // 职位层级
            case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionLevelId
              );
              break;
            // 职级范围
            case 'C8D53C139F7B44D38826E0B5A3F9F93E1':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.positionRange
              );
              break;
            // 是否特殊工种
            case 'CB4163C72FA5E45D38302983E8A66801E':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.isSpecial
              );
              break;
            // 是否关键职位
            case 'CE183DF5A547A4728A60F9AFDF3C53194':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.isKey
              );
              break;
            // 职位使命
            case 'C1F70705F5EF84FB6A82892CD4181738C':
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                temp.remark
              );
              break;
            default:
              pushControl(
                organizationTemplateCtlValue,
                templateId,
                item2,
                item3,
                ''
              );
              break;
          }
        });
      });
      return {
        positionLibrary,
        organizationTemplateCtlValue
      };
    }
  );
  await PostPositionStandard({
    positionLibraryReq
  });
};

// 新增组织弹出框自定义事件
const positionAddEmit = async (formData: any) => {
  try {
    // 获取对应模板
    const templateDetail = await PostPositionMerge({
      ids: [formData.templateId],
      ownerType: 2 // 职位模板默认传2
    });

    const jobListTemplateReq = templateDetail.map(
      (item1: any, index1: number) => {
        const temp = formData;
        const templateId = item1.id;

        const positionListModel = {
          ...temp,
          templateUseId: templateId,
          controlType: 1 // 编制类型，新增默认不编制传1
        };
        const organizationTemplateCtlValue: any = [];

        item1.collectionModel.forEach((item2: any) => {
          item2.controlModel.forEach((item3: any) => {
            switch (item3.ctlCode) {
              // 职位名称
              case 'C2818BAA63AE848AA845DA2E81ECB1843':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.name
                );
                break;
              // case 'POSITON_STAND_NAME':
              //   pushControl(formData, item2, templateId, formData.);
              //   break;
              // 职位编码
              case 'CB25F6DA9F83C4424BBC37E8756BB871E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionCode
                );
                break;
              // 编制人数
              case 'CD25749DBA68E4BF3BCA616DD63751CB7':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.headcount
                );
                break;
              // 职位类别
              case 'C63EC32DCE9CC4BE6AC7649E23234A542':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionTypeId
                );
                break;
              // 职位层级
              case 'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionLevelId
                );
                break;
              // 职位层级
              case 'C8D53C139F7B44D38826E0B5A3F9F93E1':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionRange
                );
                break;
              // 是否特殊工种
              case 'CB4163C72FA5E45D38302983E8A66801E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isSpecial
                );
                break;
              // 是否关键职位
              case 'CE183DF5A547A4728A60F9AFDF3C53194':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isKey
                );
                break;
              // 职位使命
              case 'C1F70705F5EF84FB6A82892CD4181738C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.remark
                );
                break;
              // 公司
              case 'CA8ABCC1480744557B3014C3454465A7E':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.companyId
                );
                break;
              // 部门
              case 'CED44AC9966904CD1AB546D309903727C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.organizationId
                );
                break;
              // 关联职务
              case 'C1F5AA49A78EC4B4FBD487F4D5887E576':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.relatedId
                );
                break;
              // 关联标准职位
              case 'C456DF4781B0F465F850C271F29504B1C':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.standJobId
                );
                break;
              // 选择职位说明书模板
              case 'C8B68CCFE6DAB49D088E663E467BFAB34':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.templateId
                );
                break;
              // 职位序列
              case 'CC0DAA8E0695A48489672B3E3B4DE8F1B':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.positionSequenceId
                );
                break;
              // 是否设为标准职位
              case 'C50267C6B8E104B0C91EDD25BCAE35609':
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  temp.isStand
                );
                break;
              default:
                pushControl(
                  organizationTemplateCtlValue,
                  templateId,
                  item2,
                  item3,
                  ''
                );
                break;
            }
          });
        });
        return {
          positionListModel,
          organizationTemplateCtlValue
        };
      }
    );
    await PostPosition({
      jobListTemplateReq
    });

    // 如果新增标准职位
    if (formData.isStand === 1)
      await isAddPositionStand(formData, templateDetail);
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style scoped lang="less">
.header {
  .box1 {
    margin-bottom: 10px;
    .info-title {
      color: #86909c;
    }
    // .options {
    //   position: relative;
    //   left: 50%;
    //   transform: translateX(-50%);
    // }
  }
  .box2 {
    margin-bottom: 16px;
  }
}
.collapseBtn {
  position: absolute;
  right: 0;
  // top: 60px;
  cursor: pointer;
}
:deep(.arco-collapse-item-content) {
  background-color: #fff;
}

:deep(.arco-tabs-nav-tab) {
  justify-content: center;
}

:deep(.arco-scrollbar.arco-scrollbar-type-track .arco-scrollbar-track) {
  background-color: #fff;
}
:deep(.arco-collapse-item-active > .arco-collapse-item-header) {
  border: none;
}
</style>
